<!--
 * @Author: Rachel 943701297@qq.com
 * @Date: 2022-09-04 00:13:47
 * @LastEditors: Rachel 943701297@qq.com
 * @LastEditTime: 2022-09-04 00:36:01
 * @FilePath: \JSCode\pro\DeepClone.html
 * @Description: 
 * 
 * Copyright (c) 2022 by Rachel 943701297@qq.com, All Rights Reserved. 
-->
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>深浅拷贝学习</title>
  </head>
  <body>
    <script>
      /* function deepClone(obj = {}, map = new Map()) {
        if (typeof obj !== "object") {
          return obj;
        }
        if (map.get(obj)) {
          return map.get(obj);
        }

        let result = {};
        // 初始化返回结果
        if (
          obj instanceof Array ||
          // 加 || 的原因是为了防止 Array 的 prototype 被重写，Array.isArray 也是如此
          Object.prototype.toString(obj) === "[object Array]"
        ) {
          result = [];
        }
        // 防止循环引用
        map.set(obj, result);
        for (const key in obj) {
          // 保证 key 不是原型属性
          if (obj.hasOwnProperty(key)) {
            // 递归调用
            result[key] = deepClone(obj[key], map);
          }
        }

        // 返回结果
        return result;
      } */

      //函数拷贝
      const copyObj = (obj = {}) => {
        //变量先置空
        let newobj = null;

        //判断是否需要继续进行递归
        if (typeof obj == "object" && obj !== null) {
          newobj = obj instanceof Array ? [] : {};
          //进行下一层递归克隆
          for (var i in obj) {
            newobj[i] = copyObj(obj[i]);
          }
          //如果不是对象直接赋值
        } else newobj = obj;

        return newobj;
      };

      function deepClone(tar) {
        if (typeof tar == "object" && tar != null) {
          const res = Array.isArray(tar) ? [] : {};
          for (let i in tar) {
            res[i] = deepClone(tar[i]);
          }
          return res;
        }
        return tar;
      }

      let obj = {
        n: 123,
        s: "string",
        b: true,
        objInside: {
          name: "内部obj",
        },
        u: undefined,
        f: function () {
          console.log("obj函数");
        },
      };

      let obj2 = deepClone(obj);
      obj2.n = 312;
      obj2.s = "str";
      obj2.b = false;
      obj2.objInside.name = "obj2内部obj";
      obj2.u = 1;
      obj2.f = () => {
        console.log("obj2函数");
      };
      console.log(obj);
      console.log(obj2);
    </script>
  </body>
</html>
